// 历史记录管理功能
function initHistoryFunctions(app) {
    // 扩展HttpRequestTool类，添加历史记录相关方法
    Object.assign(app, {
        async loadUrlHistory() {
            try {
                this.urlHistory = await getUrlHistory();
                this.updateUrlSuggestions();
            } catch (error) {
                console.error('加载URL历史失败:', error);
            }
        },

        // 保存完整请求到历史记录
        async saveToHistory(requestData, processedUrl) {
            if (!requestData.url || requestData.url.trim() === '') return;

            try {
                const historyItem = {
                    id: Date.now(),
                    timestamp: new Date().toISOString(),
                    originalUrl: requestData.url,
                    processedUrl: processedUrl || requestData.url,
                    method: requestData.method,
                    headers: requestData.headers,
                    body: requestData.body,
                    options: requestData.options,
                    name: this.extractTabNameFromUrl(requestData.url)
                };

                // 每次请求都新增一条历史记录，不再检查重复
                // 为每条历史记录生成唯一ID
                historyItem.id = Date.now() + Math.random();

                this.urlHistory.unshift(historyItem);

                // 限制历史记录数量，保留最近的100条
                if (this.urlHistory.length > 100) {
                    this.urlHistory = this.urlHistory.slice(0, 100);
                }

                // 保存到服务器或本地存储
                await this.saveUrlHistory();
                this.updateUrlSuggestions();
            } catch (error) {
                console.error('保存请求历史失败:', error);
            }
        },

        // 保存URL历史记录
        async saveUrlHistory() {
            try {
                await fetch('/api/history', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(this.urlHistory)
                });
            } catch (error) {
                console.log('使用本地存储保存历史记录');
                localStorage.setItem('http-tool-history', JSON.stringify(this.urlHistory));
            }
        },

        updateUrlSuggestions(filter = '') {
            const datalist = document.getElementById('url-suggestions');
            datalist.innerHTML = '';

            // 适配新的历史记录结构
            const filtered = this.urlHistory.filter(item => {
                if (typeof item === 'string') {
                    // 兼容旧格式
                    return item.toLowerCase().includes(filter.toLowerCase());
                } else {
                    // 新格式
                    return item.originalUrl.toLowerCase().includes(filter.toLowerCase()) ||
                        item.processedUrl.toLowerCase().includes(filter.toLowerCase());
                }
            }).slice(0, 10);

            filtered.forEach(item => {
                const option = document.createElement('option');
                if (typeof item === 'string') {
                    option.value = item;
                } else {
                    option.value = item.originalUrl;
                }
                datalist.appendChild(option);
            });
        },

        showUrlHistoryDialog() {
            const historyHtml = this.urlHistory.map(item => {
                if (typeof item === 'string') {
                    // 兼容旧格式
                    return `<div class="history-item" onclick="app.selectUrl('${item}')">
                        <div class="history-item-url">${item}</div>
                        <div class="history-item-method">GET</div>
                    </div>`;
                } else {
                    // 新格式 - 显示更丰富的信息
                    const timestamp = new Date(item.timestamp).toLocaleString();
                    const hasOptions = item.options && (
                        item.options.addTimestamp ||
                        item.options.addNonce ||
                        item.options.addAppId ||
                        item.options.addSignature ||
                        item.options.encryptBody ||
                        item.options.decryptResponse
                    );

                    return `<div class="history-item" data-item-id="${item.id}">
                        <div class="history-item-content" onclick="app.restoreFromHistory(${item.id})">
                            <div class="history-item-header">
                                <span class="history-item-method ${item.method.toLowerCase()}">${item.method}</span>
                                <span class="history-item-name">${item.name}</span>
                                <span class="history-item-time">${timestamp}</span>
                            </div>
                            <div class="history-item-url">${item.originalUrl}</div>
                            ${item.processedUrl !== item.originalUrl ?
                            `<div class="history-item-processed">实际请求: ${item.processedUrl}</div>` : ''}
                            ${hasOptions ? '<div class="history-item-options">包含高级选项</div>' : ''}
                        </div>
                        <div class="history-item-actions">
                            <button class="btn btn-small" onclick="app.copyAsCurl(${item.id}, event)" title="复制为CURL">复制为CURL</button>
                            <button class="btn btn-small" onclick="app.restoreFromHistory(${item.id})">恢复</button>
                            <button class="btn btn-small btn-danger" onclick="app.removeFromHistory(${item.id}, event)">删除</button>
                        </div>
                    </div>`;
                }
            }).join('');

            this.showModal('', `
                <div class="modal-header-with-actions">
                    <h3>请求历史记录</h3>
                    <button id="clear-history" class="btn btn-danger btn-small" onclick="app.clearHistory()">清空历史记录</button>
                </div>
                <div class="url-history-list">
                    ${historyHtml || '<p class="empty-state">暂无历史记录</p>'}
                </div>
            `);
        },

        selectUrl(url) {
            document.getElementById('url-input').value = url;
            this.hideModal();
        },

        // 从历史记录恢复完整请求
        restoreFromHistory(itemId) {
            const historyItem = this.urlHistory.find(item =>
                (typeof item === 'object' && item.id === itemId)
            );

            if (!historyItem) {
                this.showMessage('历史记录项未找到');
                return;
            }

            // 保存当前标签页数据
            this.saveCurrentTabData();

            // 恢复请求数据到当前标签页
            const tab = this.tabs.get(this.currentTab);
            tab.method = historyItem.method;
            tab.url = historyItem.originalUrl;
            tab.headers = historyItem.headers || {};
            tab.body = historyItem.body || '';
            tab.options = historyItem.options || this.getDefaultOptions();
            tab.name = historyItem.name;

            // 更新界面
            this.loadTabData(tab);
            this.updateTabsDisplay();

            this.hideModal();
            this.showMessage('请求已恢复到当前标签页');
        },

        // 从历史记录中删除指定项
        removeFromHistory(itemId, event) {
            if (event) {
                event.stopPropagation();
            }

            if (!confirm('确定要删除这条历史记录吗？')) {
                return;
            }

            const index = this.urlHistory.findIndex(item =>
                (typeof item === 'object' && item.id === itemId)
            );

            if (index !== -1) {
                this.urlHistory.splice(index, 1);
                this.saveUrlHistory();
                this.showMessage('历史记录已删除');
                // 重新显示历史记录对话框
                this.showUrlHistoryDialog();
            }
        },

        async clearHistory() {
            if (confirm('确定要清空所有历史记录吗？')) {
                this.urlHistory = [];
                await this.saveUrlHistory(); // 新增：同步清空到后端和本地
                this.updateUrlSuggestions();
                this.showMessage('历史记录已清空');
                // 重新显示历史记录对话框以刷新列表
                this.showUrlHistoryDialog();
            }
        },
        
        // 生成cURL命令并复制到剪贴板
        copyAsCurl(itemId, event) {
            if (event) {
                event.stopPropagation(); // 阻止事件冒泡，避免触发恢复操作
            }
            
            const historyItem = this.urlHistory.find(item => item.id === itemId);
            if (!historyItem) {
                this.showMessage('未找到历史记录项');
                return;
            }
            
            // 构建cURL命令
            let curlCmd = `curl -X ${historyItem.method} "${historyItem.processedUrl || historyItem.originalUrl}"`;
            
            // 添加请求头
            if (historyItem.headers && Object.keys(historyItem.headers).length > 0) {
                for (const [key, value] of Object.entries(historyItem.headers)) {
                    if (key && value) {
                        curlCmd += ` \\
  -H "${key}: ${value.replace(/"/g, '\\"')}"`;                        
                    }
                }
            }
            
            // 添加请求体
            if (historyItem.body && historyItem.method !== 'GET') {
                curlCmd += ` \\
  -d '${historyItem.body.replace(/'/g, "\\'")}'`;
            }
            
            // 复制到剪贴板
            navigator.clipboard.writeText(curlCmd)
                .then(() => {
                    this.showMessage('已复制cURL命令到剪贴板');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    this.showMessage('复制失败，请查看控制台');
                    // 备用方案：创建临时文本区域
                    const textarea = document.createElement('textarea');
                    textarea.value = curlCmd;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                    this.showMessage('已复制cURL命令到剪贴板');
                });
        }
    });
}

// 全局函数定义
async function getUrlHistory() {
    try {
        const response = await fetch('/api/history');
        if (response.ok) {
            return await response.json();
        }
    } catch (error) {
        console.log('使用本地存储加载历史');
    }

    // 降级到本地存储
    const history = localStorage.getItem('http-tool-history');
    return history ? JSON.parse(history) : [];
}

// 导出函数以便在其他文件中使用
window.initHistoryFunctions = initHistoryFunctions;